<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 根目录和文件地址
define('ROOT', dirname(__DIR__) . '/php');
define('F', preg_replace('/\\\/', '/', __FILE__));

// 多维超全局变量
global $_VAR, $_CONF, $_INC, $_TMP, $F;
$_VAR = $_CONF = $_TMP = array(F => []);
$_INC = array(F);

// 特别变量
$_VAR[':debug_str'] = null;

// 盘符
$_VAR[F]['arr_exp'] = explode(':', F);
$_VAR[F]['drive_letter'] = preg_match('/^(\/mnt\/[\w]+)\/(.*)/', F, $_VAR[F]['matches']) ? $_VAR[F]['matches'][1] : array_shift($_VAR[F]['arr_exp']) . ":";
define('DRIVE_LETTER', $_VAR[F]['drive_letter']);

// 索引文件
$_CONF[F]['_INDEX'] = _include(ROOT . '/index/config/files.php', '_CONF.F._INDEX');
$_CONF[F]['_INDEX'][''] = isset($_GET['index']) ? index_get() : index_cookie();
$_CONF[F]['']['_INDEX'] = var_cache($_CONF[F]['_INDEX'], '_CONF.F._INDEX');

// 服务器变量
$_TMP['_SERVER'] = $_SERVER;
$_TMP['_SERVER'][''] = array();
$_TMP['_SERVER'][''][] = array(
    'REMOTE_PORT' => $_SERVER['REMOTE_PORT'],
    'REQUEST_TIME_FLOAT' => $_SERVER['REQUEST_TIME_FLOAT'],
    'REQUEST_TIME' => $_SERVER['REQUEST_TIME'],
);
unset($_SERVER['REMOTE_PORT'],$_SERVER['REQUEST_TIME_FLOAT'],$_SERVER['REQUEST_TIME']);

$_TMP['_SERVER'][''][] = var_cache($_SERVER, '_SERVER');
$_SERVER = $_TMP['_SERVER'];

// 缓存变量相同部分
function var_cache($var, $spec = null, $key = F, $folder = 'md5')
{
    global $_VAR, $_TMP;
    $_TMP[$key] = isset($_TMP[$key]) ? array_merge($_TMP[$key], array()) : array();
    $_TMP[$key][$spec] = isset($_TMP[$key][$spec]) ? array_merge($_TMP[$key][$spec], array()) : array();
    $_TMP[$key][$spec]['array'] = isset($_TMP[$key][$spec]['array']) ? array_merge($_TMP[$key][$spec]['array'], $var) : $var;
    $_TMP[$key][$spec]['json'] = json_encode($var);
    $_TMP[$key][$spec]['md5'] = md5($_TMP[$key][$spec]['json']);
    $log_filename = $_VAR[F]['drive_letter'] . "/env/tmp/php/log/$folder/{$_TMP[$key][$spec]['md5']}.txt";
    $_TMP[$key][$spec]['cache'] = file_exists($log_filename) ? $log_filename : file_put_contents($log_filename, $_TMP[$key][$spec]['json']);
    return $_TMP[$key][$spec]['md5'];
}

// 路由索引文件指定
function index_get()
{
    global $_CONF;
    setcookie('PHP_INDEX', $_GET['index'], time()+60*60*24*30, '/');
    if (is_numeric($_GET['index'])) {
        return $_GET['index'];
    } elseif ($_GET['index']) {
       $_CONF[F]['_INDEX']['.'] = $_GET['index']; 
    }
    return '.';
}

// 路由索引文件配置
function index_cookie()
{
    global $_CONF;
    $index = isset($_COOKIE['PHP_INDEX']) ? $_COOKIE['PHP_INDEX'] : $_CONF[F]['_INDEX'][''];
    if (!is_numeric($index) && '.' != $index) {
        $_INDEX['.'] = $index;
        $index = '.';
    }
    return $index;
}

// 包含文件返回值
function _include($file, $return = false)
{
    global $_VAR, $_CONF, $_INC;
    $_INC[] = $file . ($return ? '?' . $return : '');

    if (isset($_GET['--debug'])) {
        $_VAR[':debug_str'] = debug_var($_GET['--debug'], true);
    }

    $included = include $file;
    if ($return) {
        return $included;
    }
}

// 执行代码和日志存储
function debug_eval($result = null, $log = null)
{
    global $_VAR, $_CONF, $_INC, $_TMP;
    if (isset($_GET['--phpinfo']) && is_string($_GET['--phpinfo']) && !isset($_TMP['--phpinfo'])) {
        $_TMP['--phpinfo'] = $_GET['--phpinfo'];
        eval($_GET['--phpinfo']);
    }
    if (null !== $log) {
        $log_filename = date('Y-m-d');
        $log_arr = debug_var($log, true, true, null, 'log');
        # 
        $log_srv = $log_arr['_SERVER'][0];
        unset($log_arr['_SERVER'][0]);
        # array_shift($log_arr['_SERVER']);
        # print_r($log_srv);exit;
        $log_json = json_encode($log_arr);
        # print_r($log_arr['_SERVER']);
        $md5 = md5($log_json);
        array_unshift($log_arr['_SERVER'], $log_srv);
        # print_r($log_arr['_SERVER']);exit;
        $log_new = array(
            'same' => $md5,
            'var' => $log_srv,
        );
        $log_line = json_encode($log_new);

        $log_same = $_VAR[F]['drive_letter'] . "/env/tmp/php/log/same/$md5.txt";
        $log_filename = $_VAR[F]['drive_letter'] . "/env/tmp/php/log/$log_filename.txt";

        $_VAR[F]['']['_SAME'] = var_cache($log_json, '_VAR.F._SAME', F, 'same');

        $_VAR[':debug_str'] = $log_line . ',';
        # $put_same = file_put_contents($log_same, $log_json . PHP_EOL, FILE_APPEND);
        $put_log = file_put_contents($log_filename, $_VAR[':debug_str'] . PHP_EOL, FILE_APPEND);
        
    }
    return $result;
}

// 调试变量
function debug_var($var = null, $return = null, $array = null, $ignore = null, $type = null)
{
    global $_VAR, $_CONF, $_INC;
    $_VAR[':debug_str'] = null;
    $var = $var ? : _globals(null !== $ignore ? $ignore : ['_GET', '_COOKIE', '_REQUEST', '_TMP', '__composer_autoload_files']);

    if (is_numeric($var)) {
        switch ((int) $var) {
            case 1:
                $var = $_VAR;
                break;

            case 2:
                $var = $_CONF;
                break;

            case 3:
                $var = $_INC;
                break;

            case 4:
                $var = $_TMP;
                break;

            default:
                $var = get_included_files();
                break;
        }
    }
    $var = is_array($var) ? ('log' == $type ? log_var($var, ['_VAR', '_CONF']) : $var) : $var;
    if (true === $return) {
        return $var;
    }
    $var = is_array($var) ? ($array ? print_r($var, true) : json_encode($var)) : $var;
    if ('string' === $return) {
        return $var;
    }
    echo "<textarea style='width:100%;height:100%;min-height:600px;'>$var</textarea>";
}

// 正确获取所有全局变量
function _globals(array $vars = [])
{
    $vars[] = 'GLOBALS';
    $arr = [];
    foreach ($GLOBALS as $key => $value) {
        if (!in_array($key, $vars)) {
            $arr[$key] = $value;
        }
    }
    return $arr;
}

// 日志变量过滤
function log_var(array $vars = [], array $file = [], array $root = [])
{
    $arr = [];
    foreach ($vars as $key => $value) {
        if (in_array($key, $file) && is_array($value)) {
            $ar = [];
            foreach ($value as $k => $v) {
                if (is_array($v)) {
                    $v = isset($v['']) ? $v[''] : $v;
                }
                $ar[$k] = $v;
            }
            $arr[$key] = $ar;
        } elseif (is_array($value)) {
            if ($value) {
                $arr[$key] = isset($value['']) ? $value[''] : $value;
            }
        } else {
            $arr[$key] = $value;
        }
    }
    # array_shift($arr['_SERVER']);
    return $arr;
}


# $index_key = ;
# $index_file = ;
# $index_filename = ;
# exit;
# print_r(get_defined_vars());

// 返回第一次包含文件值
return $html = _include(ROOT . "/{$_CONF[F]['_INDEX'][$_CONF[F]['_INDEX']['']]}.php", true);
